package com.mingtu.guards.activity;

import android.graphics.Point;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.TileOverlay;
import com.amap.api.maps.model.TileOverlayOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.TranslateAnimation;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.ServiceSettings;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.mingtu.common.utils.AMapToastUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.utils.StatusBarUtil;
import com.mingtu.guards.R;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.common.utils.ConvertLatlng;
import com.mingtu.guards.utils.MySPTools;
import com.mingtu.guards.utils.TileUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.MAP_INDEX;
import static com.mingtu.guards.utils.MyConstant.MAX_ZOOM;

public class ReportMapActivity extends MyBaseActivity {
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.iv_location)
    ImageView ivLocation;
    @BindView(R.id.iv_switch)
    ImageView ivSwitch;
    @BindView(R.id.status_bar_view)
    View statusBarView;
    @BindView(R.id.tv_top_tip)
    TextView tvTopTip;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    private AMap aMap;
    private List<Marker> markerList = new ArrayList<>();
    private LatLng location;
    private Marker markerInterest;
    private TileOverlayOptions tileOverlayOptions;
    private TileOverlay tileOverlay;
    private boolean isSwitch = true;
    private ImmersionBar immersionBar;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_report_map;
    }

    @Override
    protected void initView() {
        hideHeadView();
        int statusBarHeight = StatusBarUtil.getStatusBarHeight(context);
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) ivSwitch.getLayoutParams();
        lp.setMargins(0, statusBarHeight + SizeUtils.dp2px(40), SizeUtils.dp2px(15), 0);
        ivSwitch.setLayoutParams(lp);

        //沉侵式状态栏
        immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(false);  //状态栏字体是深色，不写默认为亮色
        immersionBar.navigationBarDarkIcon(false);
        immersionBar.init();

        StatusBarUtil.addStatusBarHeight(statusBarView);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getData() {

    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {


            }
        });
        String address = SPStaticUtils.getString(SPTools.address);
        String longitude = SPStaticUtils.getString(SPTools.lng);
        String latitude = SPStaticUtils.getString(SPTools.lat);


        SPStaticUtils.put(MySPTools.UPLOAF_LNG, longitude);
        SPStaticUtils.put(MySPTools.UPLOAD_LAT, latitude);
        SPStaticUtils.put(MySPTools.UPLOAF_ADDRESS, address);

        String myLng = null;
        String myLat = null;
        try {
            myLng = ConvertLatlng.getInstance().convertToSexagesimal(Double.parseDouble(longitude));
            myLat = ConvertLatlng.getInstance().convertToSexagesimal(Double.parseDouble(latitude));
            tvLocation.setText(myLng + "," + myLat);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        tvAddress.setText(address + "");

        if (!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude)) {
            location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
            //添加Marker
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(location)
                    .zIndex(MAP_INDEX)
                    .icon(BitmapDescriptorFactory.fromResource(com.mingtu.home.R.mipmap.sb_icon_wz));
            Marker marker = aMap.addMarker(markerOptions);
            markerList.add(marker);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        }

        //自定义瓦片
        tileOverlayOptions = TileUtils.getTileOverlayOptions();
        tileOverlay = aMap.addTileOverlay(tileOverlayOptions);
        initInterest();
    }

    @OnClick({R.id.iv_location, R.id.iv_switch})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_location:
                if (location != null) {
                    aMap.animateCamera(CameraUpdateFactory.changeLatLng(location));
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM));

                    markerInterest.setPosition(location);
                }
                break;
            case R.id.iv_switch:
                if (isSwitch) {
                    isSwitch = false;
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                    tileOverlay.setVisible(false);
                    immersionBar.statusBarDarkFont(true);
                    immersionBar.init();
                } else {
                    isSwitch = true;
                    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
                    tileOverlay.setVisible(true);
                    immersionBar.statusBarDarkFont(false);
                    immersionBar.init();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (aMap != null) {
            mapView.onDestroy();
        }

        if (markerList.size() > 0) {
            for (Marker marker : markerList) {
                marker.remove();
            }
            markerList.clear();
        }

        //自定义瓦片
        if (tileOverlay != null) {
            tileOverlay.setVisible(false);
            tileOverlay.remove();
        }

        super.onDestroy();
    }

    /**
     * ****************兴趣点相关逻辑***********************
     */

    private void initInterest() {
        aMap.setOnCameraChangeListener(onCameraChangeListener);

        // 添加当前坐标覆盖物
        MarkerOptions markerOptionsIntetest = new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_gps_xqd))
                .position(location)
                .zIndex(MAP_INDEX)
                .draggable(true);//设置Marker可拖动
        markerInterest = aMap.addMarker(markerOptionsIntetest);
        screenMarkerJump(markerInterest);


    }

    /**
     * 移动兴趣点监听
     */
    private AMap.OnCameraChangeListener onCameraChangeListener = new AMap.OnCameraChangeListener() {
        @Override
        public void onCameraChange(CameraPosition cameraPosition) {

            markerInterest.setPosition(cameraPosition.target);

        }

        @Override
        public void onCameraChangeFinish(CameraPosition cameraPosition) {
            LatLng latLng = cameraPosition.target;
            double lat = latLng.latitude;
            double lng = latLng.longitude;
            MyLogUtil.e("interest location", "latitude==" + lat + ",longitude==" + lng);
            String myLng = ConvertLatlng.getInstance().convertToSexagesimal(lng);
            String myLat = ConvertLatlng.getInstance().convertToSexagesimal(lat);
            tvLocation.setText(myLng + "," + myLat);
            SPStaticUtils.put(MySPTools.UPLOAD_LAT, lat + "");
            SPStaticUtils.put(MySPTools.UPLOAF_LNG, lng + "");

            screenMarkerJump(markerInterest);
            GeocodeSearch geocoderSearch = null;
            try {
                ServiceSettings.updatePrivacyShow(context, true, true);
                ServiceSettings.updatePrivacyAgree(context, true);
                geocoderSearch = new GeocodeSearch(context);
                geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {

                    @Override
                    public void onGeocodeSearched(GeocodeResult result, int rCode) {

                    }

                    @Override
                    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
                        MyLogUtil.e("formatAddress", "rCode:" + rCode);
                        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                            if (result != null && result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress() != null) {
                                String formatAddress = result.getRegeocodeAddress().getFormatAddress();
                                MyLogUtil.e("formatAddress", "formatAddress:" + formatAddress);
                                tvAddress.setText(formatAddress);
                                SPStaticUtils.put(MySPTools.UPLOAF_ADDRESS, formatAddress);
                            } else {
                                ToastUtils.showLong("对不起，没有搜索到相关数据！");
                            }
                        } else {
                            AMapToastUtil.showerror(context, rCode);
                        }

                    }
                });
                LatLonPoint lp = new LatLonPoint(lat, lng);
                RegeocodeQuery query = new RegeocodeQuery(lp, 200, GeocodeSearch.AMAP);
                geocoderSearch.getFromLocationAsyn(query);
            } catch (AMapException e) {
                e.printStackTrace();
            }

        }
    };


    /**
     * Marker动画
     */
    public void screenMarkerJump(Marker screenMarker) {
        if (screenMarker != null) {
            final LatLng latLng = screenMarker.getPosition();
            Point point = aMap.getProjection().toScreenLocation(latLng);
            point.y -= SizeUtils.dp2px(30);
            LatLng target = aMap.getProjection()
                    .fromScreenLocation(point);
            //使用TranslateAnimation,填写一个需要移动的目标点
            Animation animation = new TranslateAnimation(target);
            animation.setInterpolator(new Interpolator() {
                @Override
                public float getInterpolation(float input) {
                    // 模拟重加速度的interpolator
                    if (input <= 0.5) {
                        return (float) (0.5f - 2 * (0.5 - input) * (0.5 - input));
                    } else {
                        return (float) (0.5f - Math.sqrt((input - 0.5f) * (1.5f - input)));
                    }
                }
            });
            //整个移动所需要的时间
            animation.setDuration(600);
            //设置动画
            screenMarker.setAnimation(animation);
            //开始动画
            screenMarker.startAnimation();
        }
    }

}